package cate.game.pvp.throne.data.trial;

import cate.common.table.d.GDThrone;
import cate.game.pvp.throne.data.TBGroupData;
import cate.game.role.RoleSimpleBase;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@NoteClass("王座争霸选拔赛数据")
public class TBTrialData extends TBGroupData {

	public static final String COLLECTION = "tb-trial";

	@NoteField("选拔赛排行榜")
	public List<TBTrialRank> rankList;

	@Override
	public void init() {
		if (rankList == null) {
			rankList = new ArrayList<>();
		}
	}

	public void clear(){
		rankList.clear();
	}


	public boolean record(RoleSimpleBase snapshot, long newValue) {
		if (rankList.size() >= GDThrone.TRIAL_RANK_MAX) {
			TBTrialRank last = rankList.get(rankList.size() - 1);
			if (last.value > newValue) {
				// 没有进排行榜
				return false;
			}
		}
		// 是否已经上榜
		TBTrialRank his = findRankByUid(snapshot.uid);
		if (his != null) {
			his.owner = snapshot;
		}
		if (his != null) {
			his.read(snapshot, newValue);
		} else {
			TBTrialRank rank = new TBTrialRank(snapshot, newValue);
			if (rankList.size() >= GDThrone.TRIAL_RANK_MAX) {
				rankList.remove(rankList.size() - 1);
			}
			rankList.add(rank);
		}
		rankList.sort(Comparator.comparing((TBTrialRank a) -> -a.value).thenComparing(a -> a.recordTime));
		return true;
	}

	private TBTrialRank findRankByUid(String roleUid) {
		try {
			for (TBTrialRank rank : rankList) {
				if (StringUtils.equals(roleUid, rank.owner.uid)) {
					return rank;
				}
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	public int getRank(String uid) {
		try {
			for (int i = 0; i < rankList.size(); i++) {
				TBTrialRank rank = rankList.get(i);
				if (StringUtils.equals(rank.owner.uid, uid)) {
					return i + 1;
				}
			}
			return -1;
		} catch (Exception e) {
			return -1;
		}
	}
}
